/**
 * 
 */
package com.bridgetree.jubaocrm.ui.groups;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.bridgetree.jubaocrm.R;
import com.bridgetree.jubaocrm.model.CRMUserBaseInfo;
import com.bridgetree.jubaocrm.service.Network;
import com.bridgetree.jubaocrm.ui.Contents;
import com.bridgetree.jubaocrm.ui.LoginUtil;
import com.bridgetree.jubaocrm.ui.ProgressDialogUtil;
import com.bridgetree.jubaocrm.ui.project.XMChildActivity;
import com.bridgetree.jubaocrm.ui.widget.PullToRefreshBase.OnRefreshListener;
import com.bridgetree.jubaocrm.ui.widget.PullToRefreshListView;
import com.bridgetree.jubaocrm.util.Groups;
import com.bridgetree.jubaocrm.util.LoginError;
import com.bridgetree.jubaocrm.util.Projects;
/**
 * GroupsAnnouncementActivity
 * </p>
 * 新报备项目 2014-5-20 上午11:21:00 create
 * 
 * @since 1.0
 */
public class GroupsNewBaoBeiChildActivity extends Activity {
	private final String TAG ="GroupsAnnouncementActivity";
	private Context mContext;
	private Groups mGroups;
	private String user_id =""; 
	private String token ="";
	private ArrayList<Projects> mProjectsList;
	private GroupMemberNewBaoBeiAdapter mRuAdapter2;
	private PullToRefreshListView firstcategory2 = null;
	private ListView actualListView2;
	private int lastPos=0;
	private int scrollTopBottompr =0;
	private int pageIndexpr = 1;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.group_announcement);
		mContext =  this;
		Intent intent = getIntent();
		if (intent == null) {
			Log.e(TAG, "intent is null");
			return;
		}
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext);
		user_id = prefs.getString(Contents.KEY_PERSONAL_LOGIN_USEID, ""); 
		token = prefs.getString(Contents.KEY_PERSONAL_LOGIN_TAKEN, "");

		TextView xm_bi_tv_title =(TextView)findViewById(R.id.xm_bi_tv_title);
		if(intent.getExtras()!=null){
			mGroups = (Groups)intent.getExtras().getSerializable("groupsMain");
			xm_bi_tv_title.setText("新报备项目");
		}
		
		findViewById(R.id.xm_bi_RelativeLayout_back).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		if(mGroups!=null){
			getGroupsGongGao(1);
		}
		firstcategory2 = (PullToRefreshListView)findViewById(R.id.groups_lv);
		firstcategory2.setOnRefreshListener(new OnRefreshListener() {
			@Override
			public void onRefresh() {
				if(scrollTopBottompr == 1){
					pageIndexpr++;
					if (mGroups != null) {
						getGroupsGongGao(pageIndexpr);
					}
				}else if(scrollTopBottompr == 0){
					pageIndexpr=1;
					if (mGroups != null) {
						getGroupsGongGao(pageIndexpr);
					}
				}
			}
		});

		firstcategory2.setOnScrollListener(new OnScrollListener() {
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				if (scrollState == OnScrollListener.SCROLL_STATE_IDLE) {
					lastPos= firstcategory2.getRefreshableView().getLastVisiblePosition();
				}
			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				// TODO Auto-generated method stub
				if (firstVisibleItem + visibleItemCount == totalItemCount) {
					scrollTopBottompr = 1;
				} else if (firstVisibleItem == 0) {
					scrollTopBottompr = 0;
				}
			}
		});
		actualListView2 = firstcategory2.getRefreshableView();
	}
	
	private void openDailog(String title, final String content) {
		new AlertDialog.Builder(mContext).setTitle(title)
		.setMessage(content).setPositiveButton("确定", new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog, int which) {
				if (content != null && content.trim().equals("用户不存在")) {
					// finish();
				}
				if("登陆失效，需重新登陆".equals(content) || "join(f.username.errors)".equals(content)){
					LoginUtil.executeLoginFaild(mContext);
				}

			}
		}).show();
	}
	
	/**
	 * 获取新报备的数据1
	 * 
	 * @param pageIndex
	 */
	private void getGroupsGongGao(final int pageindex) {
		Network mNetword = new Network(mContext);
		if (!mNetword.isNetworkConnected()) {
			openDailog("网络提示", "网络未连接,请连接网络！");
		} else {
			final ProgressDialog progressDialog = ProgressDialog.show(this,
					"网络数据", "...Loading...");
		//http://crmsoap.woniuwo.cn/projects_of_group?group_id=5374743fd5ac700e4ce8f60b&user_id=cd34350bb2844077bfbd4abe5ec56f99&token=15f4b0826dc841198c30088f4a7afd90&validation=gAJ9cQAoVQZsb2NhbGVxAVUFemhfQ05xAl&page=1&t=n
			String URL = Network.API_DOMAIN + "/projects_of_group?group_id=" + mGroups.getGroup_id()+"&user_id=" + user_id+ "&token=" + token + "&validation=" + CRMUserBaseInfo.kValication+"&page="+pageindex+"&t=n";
			//http://crmsoap.woniuwo.cn/group?id=5374743fd5ac700e4ce8f60b&r=members&user_id=cd34350bb2844077bfbd4abe5ec56f99&token=15f4b0826dc841198c30088f4a7afd90&validation=gAJ9cQAoVQZsb2NhbGVxAVUFemhfQ05xAl

			RequestQueue requestQueue = Volley.newRequestQueue(mContext);
			JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
					Request.Method.GET, URL, null,
					new Response.Listener<JSONObject>() {
						@Override
						public void onResponse(JSONObject response) {
							ProgressDialogUtil.dissmis(progressDialog);
							System.out.println("获取新报备的数据1 response=" + response);
							try {
								if (!response.isNull("projects")) {
									String data = response.getString("projects");
									if (data.equals("[]")) {
										Toast.makeText(mContext, "已经到最后了~",
												Toast.LENGTH_SHORT).show();
									} else {
										org.json.JSONArray jsonArr;
										jsonArr = response.getJSONArray("projects");
										if(mProjectsList==null || pageindex==1){
											mProjectsList = new ArrayList<Projects>();
										}
										if (jsonArr.length() > 0) {
											for (int i = 0; i < jsonArr
											.length(); i++) {
												Projects mProjects = new Projects();
												JSONObject jsonObj2 = jsonArr
												.getJSONObject(i);
//												if (!jsonObj2.isNull("is_approved")) {
//													String is_approved = jsonObj2
//													.getString("is_approved");
//													mProjects.setIs_approved(is_approved);
//												}
												if (!jsonObj2.isNull("client_id")) {
													String client_id = jsonObj2
													.getString("client_id");
													mProjects.setClient_id(client_id);
												}
												if (!jsonObj2.isNull("project_id")) {
													String project_id = jsonObj2
													.getString("project_id");
													mProjects.setProject_id(project_id);
												}
												if (!jsonObj2.isNull("project_name")) {
													String project_name = jsonObj2
													.getString("project_name");
													mProjects.setProject_name(project_name);
												}
												mProjectsList.add(mProjects);
											}
										}
										mRuAdapter2 = new GroupMemberNewBaoBeiAdapter(mContext, mProjectsList);
										actualListView2.setAdapter(mRuAdapter2);
										mRuAdapter2.notifyDataSetChanged();
										if (pageindex > 1) {
											actualListView2.setSelection(lastPos);
										}
										}
									if (firstcategory2 != null) {
										firstcategory2.onRefreshComplete();
									}
								}
								if (!response.isNull("errors")) {
									String errors = response.get("errors")
									.toString();
									if (errors.equals("[]")) {
									} else {
										org.json.JSONArray jsonArr;
										if (!response.isNull("errors")) {
											LoginError mLoginError = new LoginError();
											jsonArr = response
											.getJSONArray("errors");
											if (jsonArr.length() > 0) {
												for (int i = 0; i < jsonArr
												.length(); i++) {
													JSONObject jsonObj2 = jsonArr
													.getJSONObject(i);
													if (!jsonObj2
															.isNull("desc")) {
														String desc = jsonObj2
														.getString("desc");
														mLoginError
														.setDesc(desc);
													}
													if (!jsonObj2
															.isNull("value")) {
														String value = jsonObj2
														.getString("value");
														mLoginError
														.setValue(value);
													}
												}
											}
										}
									}
								}
							} catch (NumberFormatException e) {
								e.printStackTrace();
							} catch (JSONException e) {
								e.printStackTrace();
							}
						}
					}, new Response.ErrorListener() {
						@Override
						public void onErrorResponse(VolleyError arg0) {
							ProgressDialogUtil.dissmis(progressDialog);
							System.out.println("sorry,Error");
						}
					});
			requestQueue.add(jsonObjectRequest);
		}
	}
	protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
		if(resultCode==XMChildActivity.foujue){
			getGroupsGongGao(1);
		}
	}
	
}

class GroupMemberNewBaoBeiAdapter extends BaseAdapter {
	private List<Projects>  Date = null;
	private Context context;
	private LayoutInflater mInflater;
	public HashMap<Integer, Bitmap> cachedBitmap;
	private String user_id =""; 
	private String token ="";
	private int index;
	private class GridHolder {
		ImageView xm_12_item_iv;
		TextView xm_12_item_tv;
	}
	
	@SuppressLint("UseSparseArrays")
	public GroupMemberNewBaoBeiAdapter(Context mContext,List<Projects> mAnnouncementList) {
		super();
		this.context = mContext;
		this.Date = mAnnouncementList;
		mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
		user_id = prefs.getString(Contents.KEY_PERSONAL_LOGIN_USEID, ""); 
		token = prefs.getString(Contents.KEY_PERSONAL_LOGIN_TAKEN, "");
	}

	public int getCount() {
		return Date.size();
	}

	@Override
	public Object getItem(int index) {
		return Date.get(index);
	}

	@Override
	public long getItemId(int index) {
		return index;
	}

	@Override
	public View getView(final int index, View convertView, ViewGroup parent) {
		GridHolder holder;
		if (convertView == null) {
			convertView = mInflater.inflate(R.layout.xm_12_item, null);
			holder = new GridHolder();
			holder.xm_12_item_iv = (ImageView) convertView.findViewById(R.id.xm_12_item_iv);
			holder.xm_12_item_tv = (TextView) convertView.findViewById(R.id.xm_12_item_tv);
			convertView.setTag(holder);
		} else {
			holder = (GridHolder) convertView.getTag();
		}
		
		final String xm_txt=Date.get(index).getProject_name();
		holder.xm_12_item_tv.setText(xm_txt);
//		holder.xm_12_item_iv.setVisibility(View.GONE);
//		boolean xm_flag=Date.get(index).getIs_done();
////		if(xm_flag){
//			holder.xm_12_flag_iv.setVisibility(View.INVISIBLE);
////		}else{
////			holder.xm_12_flag_iv.setVisibility(View.VISIBLE);
////		}
		
		convertView.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				getBasicInfomation(Date.get(index).getProject_id());
			}
		});
		return convertView;
	}
	
	private void openDailog(String title, String content) {
		new AlertDialog.Builder(context).setTitle(title).setMessage(content)
				.setPositiveButton("确定", null).show();
	}
	
	/**
	 * 获取基本信息
	 */
	private void getBasicInfomation(String mProjects) {
		System.out.println("项目   =   " + mProjects);
		Network mNetword = new Network(context);
		if (!mNetword.isNetworkConnected()) {
			openDailog("网络提示", "网络未连接,请连接网络！");
		} else {
			String URL = Network.API_DOMAIN
					+ "/base_info_of_project?project_id=" + mProjects
					+ "&user_id=" + user_id + "&token=" + token
					+ "&validation=" + CRMUserBaseInfo.kValication;
			final ProgressDialog progressDialog = ProgressDialog.show(context,
					"网络数据", "...Loading...");
			RequestQueue requestQueue = Volley.newRequestQueue(context);
			JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
					Request.Method.GET, URL, null,
					new Response.Listener<JSONObject>() {
						@Override
						public void onResponse(JSONObject response) {
							Log.d("JSONObject", "response:" + response);
							try {
								// System.out.println("response="+response);
								ProgressDialogUtil.dissmis(progressDialog);
								if (response.isNull("errors")
										|| response.get("errors").toString()
												.equals("[]")) {
									Projects mProjects = new Projects();
									if (!response.isNull("is_approved")) {
										boolean is_approved = Boolean.valueOf(response
												.getString("is_approved"));
										mProjects.setIs_approved(is_approved);
									}
									if (!response.isNull("client_id")) {
										String client_id = response
												.getString("client_id");
										mProjects.setClient_id(client_id);
									}
									if (!response.isNull("project_name")) {
										String project_name = response
												.getString("project_name");
										mProjects.setProject_name(project_name);
									}
									if (!response.isNull("project_id")) {
										String project_id = response
												.getString("project_id");
										mProjects.setProject_id(project_id);
									}
									if (!response.isNull("process_status")) {
										String project_status = response
												.getString("process_status");
										mProjects
												.setProcess_status(project_status);
									}

									if (!response
											.isNull("is_user_in_this_project")) {
										String is_user_in_this_project = response
												.getString("is_user_in_this_project");
										mProjects
												.setIs_user_in_this_project(Boolean
														.parseBoolean(is_user_in_this_project));
									}
									if (!response.isNull("is_final_approve")) {
										String is_final_approve = response
												.getString("is_final_approve");
										mProjects.setIs_final_approve(Boolean
												.parseBoolean(is_final_approve));
									}
									if (!response.isNull("is_approve_project")) {
										String is_approve_project = response
												.getString("is_approve_project");
										mProjects.setIs_approve_project(Boolean
												.parseBoolean(is_approve_project));

									}
									if (!response.isNull("is_creater")) {
										String is_creater = response
												.getString("is_creater");
										mProjects.setIs_creater(Boolean
												.parseBoolean(is_creater));
									}
									if (!response
											.isNull("flag_only_view_base_info")) {
										String flag_only_view_base_info = response
												.getString("flag_only_view_base_info");
										mProjects
												.setFlag_only_view_base_info(Boolean
														.parseBoolean(flag_only_view_base_info));
									}
									if (!response.isNull("is_edit_project")) {
										String is_edit_project = response
												.getString("is_edit_project");
										mProjects.setIs_edit_project(Boolean
												.parseBoolean(is_edit_project));
									}
									if (!response.isNull("approved_date")) {
										String approved_date = response
												.getString("approved_date");
										mProjects
												.setApproved_date(approved_date);
									}
									if (!response.isNull("approved_by")) {
										String approved_by = response
												.getString("approved_by");
										mProjects.setApproved_by(approved_by);
									}
									if (!response.isNull("approved_by")) {
										String approved_by = response
												.getString("approved_by");
										mProjects.setApproved_by(approved_by);
									}
									if (!response.isNull("is_view_all_projects_or_reviewers")) {
										String is_view_all_projects_or_reviewers = response
												.getString("is_view_all_projects_or_reviewers");
										mProjects.setIs_view_all_projects_or_reviewers(Boolean
														.parseBoolean(is_view_all_projects_or_reviewers));
									}
									mProjects.setUser_id(user_id);
									mProjects.setToken(token);
									Intent intent = new Intent(context,
											XMChildActivity.class);
									Bundle bundle = new Bundle();
									bundle.putSerializable("my_projects",
											mProjects);
									intent.putExtras(bundle);
									((Activity) context).startActivityForResult(intent,0);
								} else {
									String errors = response.get("errors")
											.toString();
									if (errors.equals("[]")) {
									} else {
										org.json.JSONArray jsonArr;
										if (!response.isNull("errors")) {
											LoginError mLoginError = new LoginError();
											jsonArr = response
													.getJSONArray("errors");
											if (jsonArr.length() > 0) {
												for (int i = 0; i < jsonArr
														.length(); i++) {
													JSONObject jsonObj2 = jsonArr
															.getJSONObject(i);
													if (!jsonObj2
															.isNull("desc")) {
														String desc = jsonObj2
																.getString("desc");
														openDailog("失败提示", desc);
														mLoginError
																.setDesc(desc);
													}
													if (!jsonObj2
															.isNull("value")) {
														String value = jsonObj2
																.getString("value");
														mLoginError
																.setValue(value);
													}
												}
											}
										}
									}
								}

							} catch (JSONException e) {
								e.printStackTrace();
							}
						}
					}, new Response.ErrorListener() {
						@Override
						public void onErrorResponse(VolleyError arg0) {
							Log.d("MyAnnouncementActivity", "sorry,Error");
							openDailog("失败提示", "没有找到该项目");
							ProgressDialogUtil.dissmis(progressDialog);
						}
					});
			requestQueue.add(jsonObjectRequest);
		}
	}
	
}
